#coding=utf-8

# Pyindexer 服务器
# Last Modified 2007-05-22

import web,sys,os, urllib, threading, base64, time, string
import index,database,EncodingConvert as ec,vglobals

urls = (
    '/','searchhome',
    '/search','searchresults',
    '/snapshot','snapshot',
    '/statistics','statistics',
    '/redir','redir',
    '/folder','folder',
    '/config','config',
    '/updatecfg','updatecfg'
    )

global starter

sys.setdefaultencoding('gbk')
encoding = 'utf-8'
web.webapi.internalerror = web.debugerror

# Redirect stdout to response outputter
class base:
     def __init__(self):
         reload(sys)
         sys.stdout = web.webapi.outputter(sys.stdout)

           
class config(base):
    def GET (self):
        rsize = vglobals.RESULT_PER_PAGE
        web.header("Content-Type",'text/html; charset=gb2312')
        render = web.template.render('templates/',cache=False)
        attributes = {}
        attlist = []
        vallist = []
        attindex = {}
        # populate int and float vars
        for attr in dir(vglobals):
            val = getattr(vglobals,attr)
            if type(val) in [type(0),type(0.1),type([])] and \
               attr not in ['__builtins__','DICT','INDEXLIST']:
                   attlist.append(attr)
                   attindex[attr] = val
        attlist.sort(cmp= lambda a,b:cmp(type(getattr(vglobals,a)),type(getattr(vglobals,b)) ))
        for i in range(len(attlist)):vallist.append(attindex[attlist[i]])
        print render.config(vallist,attlist,**globals()['__builtins__'])


class updatecfg(base):
    def GET(self):
        input = web.input()
        vlist = dir(vglobals)
        cmd = 'import vglobals\n'
        for k in input.iterkeys():
            val = input[k]
            # change current global configure
            cmd += 'vglobals.'+k+'='+val+'\n'
        try:   
                exec(cmd+'\n')
        except Exception,ext:
                print Exception,ext

        info = '''<SCRIPT LANGUAGE="JavaScript">
             alert("Configuration updated.");   
        </SCRIPT>
        <meta http-equiv="refresh" content="0;URL=/">
        '''
        print info
        # overwrite source code        
        try:
            if input.save:
                change_config(input)    
        except Exception , inst:
                pass

class searchhome(base):
    def GET (self):
        rsize = vglobals.RESULT_PER_PAGE
        web.header("Content-Type",'text/html; charset=gb2312')
        render = web.template.render('templates/',cache=False)
        statics = None
        try:statics = app_statics()
        except Exception:statics = None
        if statics == None:
            return
        else:
            print render.searchhome(statics,rsize)

class app_statics:
    def __init__(self):
        db = database.wait_for_lock(block=False)
        if db == None: raise Exception('db locked')
        doc_count = db.getDocCount()
        last_index = db.getLastDoc()
        self.count = str(doc_count)
        self.count = bsplite(self.count)
        self.indexsize = bsplite(str(os.path.getsize('index/index.db')))
        self.lastdoc = str(last_index)
        
     
def bsplite(stri):
        b = []
        for k in stri:b.append(k)
        s = range(len(stri),0,-3)
        for k in s:
            b.insert(k,',')
        return ''.join(b)[:-1]

class statistics(base):
        def GET(self):
           web.header("Content-Type",'text/html; charset='+encoding)
           render = web.template.render('templates/',cache=False)
           statics = app_statics()
           print render.statistics(statics)     
        
class snapshot(base):
    def GET (self):
        input = web.input()
        docid = input.c
        hdb = database.wait_for_lock(block=False)
        if not hdb:return
        index.db = hdb
        text = index.db.getSnap(base64.b64decode(docid))
        if not text:
            print "No such snapshot.",base64.b64decode(docid)
        else:
            sys.setdefaultencoding(text[1])
            web.header("Content-Type",'text/plain; charset=UTF-8')  
            str_time = time.ctime(text[2])
            str_info = 'Snapshot created at : '
            len_split = len(str_time) + len(str_info)
            print str_info + str_time+'\n'+('-'*len_split)+'\n\n\n'+text[0]
            sys.setdefaultencoding(encoding)
        
class searchresults(base):
    def GET (self):
        rsize = vglobals.RESULT_PER_PAGE
        web.header("Content-Type",'text/html; charset=utf-8')
        input = web.input()
        search = input.s
        search = string.lower(search)
        if not search or len(search) < 2 :
            web.seeother('/')
        start = int(input.begin)
        size = int(input.size)
        hdb = database.wait_for_lock(block=False)
        if not hdb:return
        index.db = hdb
        tstart = time.time()
        results,has_next,rscount = index.search(search,start,size)
        tcost = str(time.time() - tstart)[:4]
        rssize = len(results)
        render = web.template.render('templates/',cache=False)
        nurl = '/search?'+urllib.urlencode( {'s':search, 'begin':start+size, 'size':size } 
        )
        search = ec.zh2utf8(search)[1]
        if not results or len(results) < 1:
           results=None
           info='Nothing found.'
           print render.searchresults(search,results,info,start,size,has_next,start+size,rssize,nurl,rsize,tcost,rscount)
        else:
           info = ''
           print render.searchresults(search,results,info,start,size,has_next,start+size,rssize,nurl,rsize,tcost,rscount)


        
class redir(base):
      def GET(self):
          filename = web.input().p
          cmd = '"'+base64.b64decode(filename)+'"'
          cmd = ec.zh2gbk(cmd)[1]
          os.system(cmd)


class folder(base):
      def GET(self):
          filename = web.input().p
          filename = base64.b64decode(filename)
          cmd = 'explorer "'+ filename + '"'
          cmd = ec.zh2gbk(cmd)[1]
          os.system(cmd)


def main ():
    web.run(urls,globals(),web.reloader)


def change_config(kw):
    code_lines = open('vglobals.py','r').readlines()
    for i in range(len(code_lines)):
        nk = code_lines[i].split('=')
        for var in kw.iterkeys():
              if nk and len(nk) == 2:
                  if nk[0].strip() == var:
                      code_lines[i] = var + ' = ' + kw[var] + '\n'
                    
    f = open('vglobals.py','w')
    f.writelines(code_lines)
    f.flush();f.close()



if __name__ == '__main__':
    main()



	